import 'package:efood_multivendor/controller/auth_controller.dart';
import 'package:efood_multivendor/controller/category_controller.dart';
import 'package:efood_multivendor/controller/user_controller.dart';
import 'package:efood_multivendor/helper/date_converter.dart';
import 'package:efood_multivendor/helper/launch_helper.dart';
import 'package:efood_multivendor/helper/responsive_helper.dart';
import 'package:efood_multivendor/helper/route_helper.dart';
import 'package:efood_multivendor/helper/size_config.dart';
import 'package:efood_multivendor/util/dimensions.dart';
import 'package:efood_multivendor/util/styles.dart';
import 'package:efood_multivendor/view/base/age_dialog.dart';
import 'package:efood_multivendor/view/base/custom_image.dart';
import 'package:efood_multivendor/view/screens/home/widget/category_pop_up.dart';
import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:shimmer_animation/shimmer_animation.dart';

class CategoryView extends StatelessWidget {
  final CategoryController categoryController;
  CategoryView({required this.categoryController});

  static const String AlcoholDrinks = 'alcohol';
  static const int YearInHour = 8760;
  @override
  Widget build(BuildContext context) {
    ScrollController _scrollController = ScrollController();

    return Column(
      children: [
        Row(
          children: [
            Expanded(
              child: SizedBox(
                height: 95,
                child: categoryController.categoryList?.isNotEmpty == true
                    ? ListView.builder(
                        controller: _scrollController,
                        itemCount: categoryController.categoryList!.length,
                        padding: EdgeInsets.only(
                            left: Dimensions.PADDING_SIZE_EXTRA_SMALL),
                        physics: BouncingScrollPhysics(),
                        scrollDirection: Axis.horizontal,
                        itemBuilder: (context, index) {
                          return categoryController.categoryList![index].name
                                          ?.toLowerCase()
                                          .compareTo(AlcoholDrinks) ==
                                      0 &&
                                  !Get.find<AuthController>().isLoggedIn()
                              ? SizedBox()
                              : Padding(
                                  padding:
                                      EdgeInsets.symmetric(horizontal: 0.2.h),
                                  child: InkWell(
                                    onTap: () async {
                                      Function() callback = () {
                                        Get.find<CategoryController>()
                                            .clearResList();
                                        Get.toNamed(
                                            RouteHelper.getCategoryProductRoute(
                                          categoryController
                                              .categoryList![index].id!,
                                          categoryController
                                              .categoryList![index].name!,
                                        ));
                                      };
                                      String? websiteUrl = categoryController
                                          .categoryList?[index].url;
                                      if (websiteUrl != null &&
                                          websiteUrl.trim().isNotEmpty) {
                                        LaunchHelper.launchByBrowser(
                                            websiteUrl);
                                      } else if (categoryController
                                              .categoryList?[index].name
                                              ?.toLowerCase()
                                              .compareTo(AlcoholDrinks) ==
                                          0) {
                                        if (Get.find<UserController>()
                                                .userInfoModel
                                                ?.birthDate
                                                ?.isNotEmpty ==
                                            true) {
                                          DateTime? birthday = DateTime.parse(
                                              Get.find<UserController>()
                                                  .userInfoModel!
                                                  .birthDate!);
                                          if ((DateTime.now()
                                                      .difference(birthday)
                                                      .inHours /
                                                  YearInHour) >=
                                              21) {
                                            callback();
                                          } else {
                                            Get.dialog(
                                                AgeDialog(callback: callback));
                                          }
                                        } else {
                                          Get.dialog(AgeDialog(
                                            callback: callback,
                                          ));
                                        }
                                      } else {
                                        callback();
                                      }
                                      await FirebaseAnalytics.instance.logEvent(
                                          name: 'category_clicked',
                                          parameters: {
                                            'timestamp': DateConverter
                                                    .getCurrentTimeInGmtPlus3()
                                                .toString(),
                                            'categoryID': categoryController
                                                .categoryList![index].id
                                                .toString()
                                          });
                                    },
                                    child: SizedBox(
                                      width: 80,
                                      child: Column(children: [
                                        Container(
                                          margin: EdgeInsets.only(
                                            left: index == 0
                                                ? 0
                                                : Dimensions
                                                    .PADDING_SIZE_EXTRA_SMALL,
                                            right: Dimensions
                                                .PADDING_SIZE_EXTRA_SMALL,
                                          ),
                                          child: ClipRRect(
                                            borderRadius: BorderRadius.circular(
                                                Dimensions.RADIUS_SMALL),
                                            child: CustomImage(
                                              image: categoryController
                                                  .categoryList![index].image!,
                                              height: 50,
                                              width: 50,
                                              fit: BoxFit.cover,
                                            ),
                                          ),
                                        ),
                                        SizedBox(
                                            height: Dimensions
                                                    .PADDING_SIZE_EXTRA_SMALL *
                                                0.1.h),
                                        Padding(
                                          padding: EdgeInsets.only(
                                              right: index == 0
                                                  ? Dimensions
                                                      .PADDING_SIZE_EXTRA_SMALL
                                                  : 0),
                                          child: Text(
                                            categoryController
                                                    .categoryList?[index]
                                                    .name ??
                                                '',
                                            style:
                                                sfMedium.copyWith(fontSize: 13),
                                            maxLines: 2,
                                            overflow: TextOverflow.ellipsis,
                                            textAlign: TextAlign.center,
                                          ),
                                        ),
                                      ]),
                                    ),
                                  ),
                                );
                        },
                      )
                    : CategoryShimmer(categoryController: categoryController),
              ),
            ),
            ResponsiveHelper.isMobile(context)
                ? SizedBox()
                : categoryController.categoryList != null
                    ? Column(
                        children: [
                          InkWell(
                            onTap: () {
                              showDialog(
                                  context: context,
                                  builder: (con) => Dialog(
                                      child: Container(
                                          height: 550,
                                          width: 600,
                                          child: CategoryPopUp(
                                            categoryController:
                                                categoryController,
                                          ))));
                            },
                            child: Padding(
                              padding: EdgeInsets.only(
                                  right: Dimensions.PADDING_SIZE_SMALL),
                              child: CircleAvatar(
                                radius: 35,
                                backgroundColor: Theme.of(context).primaryColor,
                                child: Text('view_all'.toString(),
                                    style: TextStyle(
                                        fontSize:
                                            Dimensions.PADDING_SIZE_DEFAULT,
                                        color: Theme.of(context)
                                            .colorScheme
                                            .secondary)),
                              ),
                            ),
                          ),
                          SizedBox(
                            height: 10,
                          )
                        ],
                      )
                    : CategoryAllShimmer(categoryController: categoryController)
          ],
        ),
      ],
    );
  }
}

class CategoryShimmer extends StatelessWidget {
  final CategoryController categoryController;
  CategoryShimmer({required this.categoryController});

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: 75,
      child: ListView.builder(
        itemCount: 14,
        padding: EdgeInsets.only(left: Dimensions.PADDING_SIZE_SMALL),
        physics: BouncingScrollPhysics(),
        shrinkWrap: true,
        scrollDirection: Axis.horizontal,
        itemBuilder: (context, index) {
          return Padding(
            padding: EdgeInsets.only(right: Dimensions.PADDING_SIZE_SMALL),
            child: Shimmer(
              duration: Duration(seconds: 2),
              enabled: categoryController.categoryList == null,
              child: Column(children: [
                Container(
                  height: 50,
                  width: 50,
                  decoration: BoxDecoration(
                    color: Colors.grey[300],
                    borderRadius:
                        BorderRadius.circular(Dimensions.RADIUS_SMALL),
                  ),
                ),
                SizedBox(height: 5),
                Container(height: 10, width: 50, color: Colors.grey[300]),
              ]),
            ),
          );
        },
      ),
    );
  }
}

class CategoryAllShimmer extends StatelessWidget {
  final CategoryController categoryController;
  CategoryAllShimmer({required this.categoryController});

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: 75,
      child: Padding(
        padding: EdgeInsets.only(right: Dimensions.PADDING_SIZE_SMALL),
        child: Shimmer(
          duration: Duration(seconds: 2),
          enabled: categoryController.categoryList == null,
          child: Column(children: [
            Container(
              height: 50,
              width: 50,
              decoration: BoxDecoration(
                color: Colors.grey[300],
                borderRadius: BorderRadius.circular(Dimensions.RADIUS_SMALL),
              ),
            ),
            SizedBox(height: 5),
            Container(height: 10, width: 50, color: Colors.grey[300]),
          ]),
        ),
      ),
    );
  }
}
